﻿// LkProgramExecuter.cs
// Copyright 2009 Edgar Said Hernández Sánchez (Limo Wan Kenobi)
// limowankenobi@gmail.com
// http://lnkarel.sourceforge.net/
// http://limotonterias.blogspot.com/

/**
 * This file is part of LNKarel.
 *  
 * LNKarel is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * LNKarel is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with LNKarel.  If not, see <http://www.gnu.org/licenses/>.
 **/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LMSoft.NKarel.Core
{
    public class LkProgramExecuter
    {
        private int apuntador = 0;
        
        public LkEnsemblerProgram Program { get; set; }

        public ILkWorld World { get; set; }

        public ILkPainter Painter { get; set; }

        private LkProgramExecuter()
        {
        }

        public LkProgramExecuter(LkEnsemblerProgram program, ILkWorld world)
            : this(program, world, null)
        {
        }

        public LkProgramExecuter(LkEnsemblerProgram program, ILkWorld world, ILkPainter painter)
        {
            Program = program;
            World = world;
            Painter = painter;
        }

        public void Step()
        {
            LkEnsambler instruccion = Program.NextInstruction();

            try
            {
                switch (instruccion)
                {
                    case LkEnsambler.Paso:
                        World.KarelStep();
                        break;
                    default:
                        throw new LkExecutionProgramException("Instruccion Desconocida");
                }

                if (Painter != null)
                {
                    Painter.Paint(World);
                }
            }
            catch (LkExecutionProgramException ex)
            {
                throw ex;
            }
        }

        public void Run(int steps)
        {
            int i = 0;

            while (i < steps && !Program.ExecutionTerminated)
            {
                Step();
            }
        }

        public void Run()
        {
            while (!Program.ExecutionTerminated)
            {
                Step();
            }
        }
    }
}
